// 表单逻辑
import { evalExpression, getExpression } from '../../utils/expression'

// 逻辑触发规则保存 key为条件字段ID value为触发规则表达式 监听key的字段值发生变化时 进行逻辑判断 成立则吧对应的字段显示
let logicTriggerRules = {}

// 默认要满足条件才显示的字段
let hiddenFormItemIds = new Map()

/**
 * 解析表单逻辑
 * @param data
 */
export function parserFormLogic(data) {
  console.log(data)
  let logicItemList = data.formLogic ? data.formLogic.scheme : []
  logicItemList.forEach((item) => {
    logicShowTriggerHandle(item)
  })
  return { logicTriggerRules, hiddenFormItemIds }
}

/**
 * 获取满足条件的表单数据
 * logicTriggerRules 对象 {}
 * {
 *   "radio1677384789963": [
 *     {
 *         "triggerFormItemId": "goods_select1677384984064", // 触发显示的字段ID
 *         "logicExpression": "radio1677384789963 eq 1  " // 逻辑表达式
 *     },
 *     {
 *         "triggerFormItemId": "goods_select1677384986954",
 *         "logicExpression": "radio1677384789963 eq 2  "
 *     }
 * ]
 * }
 */
export function getFormLogicData(formData, logicTriggerRules) {
  Object.keys(logicTriggerRules).forEach((key) => {
    const rules = logicTriggerRules[key]
    if (rules && Array.isArray(rules)) {
      for (let rule of rules) {
        const flag = evalExpression(formData, rule.logicExpression)
        if (!flag) {
          delete formData[rule.triggerFormItemId]
        }
      }
    }
  })
  return formData
}

/**
 * 处理逻辑显示数据
 */
function logicShowTriggerHandle(logicItem) {
  console.log(logicItem)
  if (!logicItem) {
    return
  }
  // 建立触发关系 该字段值发生变化时 哪些问题需要进行逻辑判断 确定是否显示
  logicItem.triggerList?.forEach((trigger) => {
    hiddenFormItemIds.set(trigger.formItemId, trigger)
    logicItem.conditionList.forEach((item) => {
      if (Object.keys(item).length === 0) {
        return
      }
      let rules = logicTriggerRules[item.formItemId]
      if (!rules) {
        rules = []
      }
      let condition = logicItem.conditionList[1]
      rules.push({
        // 被触发显示的字段的ID
        triggerFormItemId: trigger.formItemId, //  显示逻辑表达式
        // 第二个条件
        logicExpression: getExpression(logicItem.conditionList, condition ? condition.relation : 'AND')
      })
      logicTriggerRules[item.formItemId] = rules
    })
  })
}
